"use strict"

var Router = require('koa-router');
var config = require('../../../config/config.js');
var Ware = require('../../../model/ware.js');
var WareDao = require('../../../dao/mongo/ware.js');

console.log('router:' + config.baseUrl + '/v1/ware');

var router = new Router({
    prefix: config.baseUrl + '/v1/ware'
});

router.get('/test', function*() {
    console.log('%s %s', this.method, this.url);
    this.body = 'test work fine';
});

/**
 * save ware
{
    "name": "面部滋润补水护理",
    "price": 100,
    "cateName":["面部护理","面部护理A"]
    "category": [
        "xxx",
        "xxx"
    ]
}
*/

router.post('/', function*() {
    console.log(this.request.body);
    // this.body = this.request.body; //echo
    // return;

    var inParams = this.request.body;
    inParams = JSON.parse(inParams);
    var ware = new Ware({
        name: inParams.name,
        price: inParams.price || null,
        cateName: inParams.cateName,
        category: inParams.category || []
    });

    console.log(ware);

    // 
    try {
        var result = yield WareDao.save(ware);
        this.body = JSON.stringify(result);
    } catch (e) {
        this.body = 'save ware error ' + e.toString();
    }
});


router.get('/:id', function*() {
    console.log(this.params.id);
    var ware = yield WareDao.findById(this.params.id);
    this.body = ware;
});

module.exports = router;